package com.fhminyi.GUI;

import com.fhminyi.dao.CommentDao;
import com.fhminyi.model.Comment;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;

public class CommentManagementFrame extends JFrame {
    private CommentDao commentDao = new CommentDao();
    private JList<Comment> commentsList;
    private DefaultListModel<Comment> listModel;
    private JButton deleteButton;

    public CommentManagementFrame() {
        setTitle("评论管理");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        listModel = new DefaultListModel<>();
        commentsList = new JList<>(listModel);
        JScrollPane scrollPane = new JScrollPane(commentsList);

        deleteButton = new JButton("删除评论");
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Comment selectedComment = commentsList.getSelectedValue();
                if (selectedComment != null) {
                    int selectedOption = JOptionPane.showConfirmDialog(CommentManagementFrame.this, "确定要删除评论吗？", "确认删除", JOptionPane.YES_NO_OPTION);
                    if (selectedOption == JOptionPane.YES_OPTION) {
                        try {
                            commentDao.deleteComment(selectedComment.getCommentId());
                            listModel.removeElement(selectedComment);
                        } catch (SQLException ex) {
                            JOptionPane.showMessageDialog(CommentManagementFrame.this, "删除评论失败", "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                }
            }
        });

        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(deleteButton, BorderLayout.SOUTH);

        loadComments();

        add(panel);
    }

    private void loadComments() {
        listModel.clear();
        try {
            List<Comment> comments = commentDao.getAllComments();
            for (Comment comment : comments) {
                listModel.addElement(comment);
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "加载评论失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}